//
//  DrawView.m
//  08-核心动画-cakeyframeanimation
//
//  Created by J on 16/2/23.
//  Copyright © 2016年 J. All rights reserved.
//

#import "DrawView.h"
#define angle2Random(angle) ((angle)/180.0*M_PI)

@interface DrawView ()
@property(nonatomic,strong)UIBezierPath* path ;

@end

@implementation DrawView


- (void)drawRect:(CGRect)rect {
    // Drawing code
    
    [self.path stroke];

    
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
//    //获取手指的触摸点
    CGPoint curP = [[touches anyObject]locationInView:self];
    //创建路径
    
    UIBezierPath* path = [UIBezierPath bezierPath];
    self.path = path;
    [path moveToPoint:curP];//设置起点
    
}


- (void)touchesMoved:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    
    
    //获取手指的触摸点
    CGPoint curP = [[touches anyObject]locationInView:self];
    //创建路径
    [self.path addLineToPoint:curP];

    [self setNeedsDisplay];
    

}

- (void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
    //给imageView添加核心动画
    //添加核心动画
    CAKeyframeAnimation* ani = [CAKeyframeAnimation animation];
    //    ani.keyPath = @"transform.rotation";
    ani.keyPath = @"position";
    //让动画绕着路径走
    ani.path = self.path.CGPath;
    
    ani.values = @[@(angle2Random(-5)),@(angle2Random(10)),@(angle2Random(-5))];
//    ani.repeatCount = CGFLOAT_MAX;
    //设置动画完成的时候不要移除动画
    ani.removedOnCompletion = NO;
    
    //动画执行完成要保持最新的效果
    ani.fillMode = kCAFillModeForwards;
    
//    self.subviews.firstObject.layer.anchorPoint = CGPointZero;
    [self.subviews.firstObject.layer addAnimation:ani forKey:nil];
    

    
}


@end
